"""
Report generation node - creates final natural language report.
"""
from typing import Dict, Any
from langchain_core.prompts import ChatPromptTemplate
from ..tools.llm_factory import create_llm


def generate_report(state: Dict[str, Any]) -> Dict[str, Any]:
    """
    Generate a comprehensive natural language report.

    Args:
        state: Current state dict

    Returns:
        Updated state dict with final report
    """
    config = state.get('config', {})
    enable_llm = config.get('enable_llm_reasoning', True)

    if not enable_llm:
        state['report'] = _generate_simple_report(state)
        state['next_action'] = 'end'
        return state

    # Create LLM using factory (supports OpenRouter and OpenAI)
    # Use slightly higher temperature for more creative report writing
    report_config = {**config, 'temperature': config.get('temperature', 0.3)}
    llm = create_llm(config=report_config)

    # Prepare data for report
    attribution_result = state.get('attribution_result', {})
    root_causes = attribution_result.get('root_causes', [])
    summary = attribution_result.get('summary', '')
    recommendations = attribution_result.get('recommendations', [])

    # Prepare data tables for better visualization
    data_tables = _prepare_data_tables(state)

    # Create prompt
    prompt = ChatPromptTemplate.from_messages([
        ("system", """You are an expert data analyst creating executive-friendly reports.

Generate a clear, concise attribution analysis report based on the findings.

Structure the report with:
1. Executive Summary (2-3 sentences)
2. Key Findings (bullet points)
3. Data Analysis (use the provided Markdown tables)
4. Root Cause Analysis (detailed explanation with data support)
5. Recommendations (actionable next steps)

IMPORTANT FORMATTING REQUIREMENTS:
- Use Markdown tables to present data (the tables are provided in the data section)
- Use bullet points for lists
- Use headers (##, ###) to structure sections
- Include specific numbers and percentages to support your analysis
- Focus on business impact with data-driven insights

Use clear, non-technical language accessible to business stakeholders.
"""),
        ("user", """Create an attribution analysis report for the following:

User Query: {query}
Target Metric: {target_metric}
Analysis Period: {time_range}

Summary: {summary}

Data Tables (use these in your report):
{data_tables}

Root Causes:
{root_causes}

Recommendations:
{recommendations}

Please generate a comprehensive report in CHINESE with proper Markdown formatting, including the data tables.""")
    ])

    # Format root causes
    root_causes_text = "\n".join([
        f"- {rc.get('cause', 'Unknown')}: {rc.get('evidence', 'N/A')} "
        f"(Impact: {rc.get('impact', 'unknown')}, Confidence: {rc.get('confidence', 0):.0%})"
        for rc in root_causes
    ])

    recommendations_text = "\n".join([
        f"- {rec}" for rec in recommendations
    ])

    # Invoke LLM
    chain = prompt | llm
    response = chain.invoke({
        "query": state.get('query', 'N/A'),
        "target_metric": state.get('target_metric', 'unknown'),
        "time_range": str(state.get('time_range', 'unknown')),
        "summary": summary,
        "data_tables": data_tables,
        "root_causes": root_causes_text or "No specific root causes identified.",
        "recommendations": recommendations_text or "No specific recommendations."
    })

    state['report'] = response.content

    # Store LLM response
    if 'llm_responses' not in state:
        state['llm_responses'] = []
    state['llm_responses'].append(response.content)

    state['next_action'] = 'end'
    return state


def _prepare_data_tables(state: Dict[str, Any]) -> str:
    """
    Prepare Markdown tables from analysis data.

    Args:
        state: Current state dict

    Returns:
        Formatted Markdown tables as string
    """
    tables = []

    # Table 1: Anomaly Summary
    anomalies = state.get('anomalies', [])
    if anomalies:
        tables.append("### 异常检测汇总\n")
        tables.append("| 日期 | 实际值 | 预期值 | 偏差 | 严重程度 |")
        tables.append("|------|--------|--------|------|----------|")

        for anomaly in anomalies[:5]:  # Top 5 anomalies
            date = str(anomaly.get('timestamp', 'N/A'))[:10]
            actual = f"{anomaly.get('actual_value', 0):,.2f}"
            expected = f"{anomaly.get('expected_value', 0):,.2f}"
            deviation = f"{anomaly.get('deviation_percentage', 0):.1f}%"
            severity = anomaly.get('severity', 'unknown')

            # 中文严重程度
            severity_cn = {
                'low': '低',
                'medium': '中',
                'high': '高',
                'critical': '严重'
            }.get(severity, severity)

            tables.append(f"| {date} | {actual} | {expected} | {deviation} | {severity_cn} |")

        tables.append("")  # Empty line

    # Table 2: Drill-Down Contributors
    drill_path = state.get('drill_down_path', [])
    if drill_path:
        for level_idx, drill in enumerate(drill_path[:2]):  # Show first 2 levels
            dimension = drill.get('dimension', 'unknown')
            contributors = drill.get('top_contributors', [])

            if contributors:
                tables.append(f"### 维度下钻分析 - {dimension}\n")
                tables.append("| 维度值 | 指标值 | 基准值 | 变化率 | 贡献度 |")
                tables.append("|--------|--------|--------|--------|--------|")

                for contrib in contributors[:5]:  # Top 5
                    value = contrib.get('value', 'N/A')
                    metric_val = f"{contrib.get('metric_value', 0):,.2f}"
                    baseline_val = f"{contrib.get('baseline_value', 0):,.2f}" if contrib.get('baseline_value') else 'N/A'
                    change = f"{contrib.get('change_rate', 0) * 100:+.1f}%" if contrib.get('change_rate') is not None else 'N/A'
                    contribution = f"{contrib.get('contribution_percentage', 0):.1f}%"

                    tables.append(f"| {value} | {metric_val} | {baseline_val} | {change} | {contribution} |")

                tables.append("")  # Empty line

    # Table 3: Metric Decomposition
    decomposition = state.get('decomposition')
    if decomposition:
        tables.append("### 指标拆解分析\n")
        tables.append("| 组成部分 | 当前值 | 变化量 | 贡献度 |")
        tables.append("|----------|--------|--------|--------|")

        components = decomposition.get('components', {})
        changes = decomposition.get('component_changes', {})
        contributions = decomposition.get('component_contributions', {})

        for component in components:
            current = f"{components.get(component, 0):,.2f}"
            change = f"{changes.get(component, 0):+,.2f}"
            contrib = f"{contributions.get(component, 0) * 100:+.1f}%"

            tables.append(f"| {component} | {current} | {change} | {contrib} |")

        tables.append("")  # Empty line

    # Table 4: Root Causes Summary
    attribution_result = state.get('attribution_result', {})
    root_causes = attribution_result.get('root_causes', [])
    if root_causes:
        tables.append("### 根因分析汇总\n")
        tables.append("| 根本原因 | 影响程度 | 置信度 |")
        tables.append("|----------|----------|--------|")

        for rc in root_causes[:5]:  # Top 5
            cause = rc.get('cause', 'Unknown')
            impact = rc.get('impact', 'unknown')
            confidence = f"{rc.get('confidence', 0):.0%}"

            # 中文影响程度
            impact_cn = {
                'low': '低',
                'medium': '中',
                'high': '高'
            }.get(impact, impact)

            tables.append(f"| {cause} | {impact_cn} | {confidence} |")

        tables.append("")  # Empty line

    if not tables:
        return "暂无数据表格"

    return "\n".join(tables)


def _generate_simple_report(state: Dict[str, Any]) -> str:
    """Generate a simple text report without LLM (with Markdown tables)."""
    sections = []

    sections.append("# 归因分析报告\n")

    # Executive Summary
    sections.append("## 执行摘要")
    sections.append(f"分析指标：{state.get('target_metric', 'metric')}")
    sections.append(f"分析期间：{state.get('time_range', 'unknown')}\n")

    # Add data tables
    data_tables = _prepare_data_tables(state)
    if data_tables != "暂无数据表格":
        sections.append("## 数据分析")
        sections.append(data_tables)

    # Root causes
    attribution_result = state.get('attribution_result', {})
    root_causes = attribution_result.get('root_causes', [])
    if root_causes:
        sections.append("## 根本原因")
        for rc in root_causes:
            sections.append(f"### {rc.get('cause', 'Unknown')}")
            sections.append(f"- **证据**: {rc.get('evidence', 'N/A')}")
            sections.append(f"- **影响**: {rc.get('impact', 'unknown')}")
            sections.append(f"- **置信度**: {rc.get('confidence', 0):.0%}\n")

    # Recommendations
    recommendations = attribution_result.get('recommendations', [])
    if recommendations:
        sections.append("## 建议措施")
        for i, rec in enumerate(recommendations, 1):
            sections.append(f"{i}. {rec}")

    return "\n".join(sections)
